import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/edit_text_field.dart';
import 'package:qunaimedical/components/item_add.dart';
import 'package:qunaimedical/components/item_image_preview.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/category.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

class MomentCreatePage extends StatefulWidget {
  final List<Category> categories;

  const MomentCreatePage({Key key, @required this.categories})
      : super(key: key);

  @override
  _MomentCreatePageState createState() => _MomentCreatePageState();
}

class _MomentCreatePageState extends State<MomentCreatePage> {
  static String _tag = '_MomentCreatePageState';
  TextEditingController _contentController = TextEditingController();
  TextEditingController _titleController = TextEditingController();

  /// 选中的图片
  List<Asset> _images = <Asset>[];

  /// 用户上传的图片路径
  List<String> _uploadedImages = [];

  /// 最多选9张图片
  int maxImageCount = 9;

  /// 类别索引
  int _categoryIndex;

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }

  /// 选择类别
  void _selectCategory(BuildContext context) async {
    CommonUtils.hideKeyboard(context);
    int value = await DialogUtils.showSelectOptionDialog(
        context, '选择类别', widget.categories.map((e) => e.label).toList(),
        selectedIndex: _categoryIndex);
    if (mounted) {
      setState(() {
        _categoryIndex = value;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('发帖'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.send),
            onPressed: () {
              _send();
            },
          )
        ],
      ),
      body: ListView(
        children: <Widget>[
          InkWell(
            child: PrimaryLabel(
              '类别',
              trailing: Row(
                children: [
                  Text(
                    _categoryIndex == null
                        ? '请选择'
                        : widget.categories[_categoryIndex].label,
                    style: TextStyle(
                        color: _categoryIndex == null
                            ? Colors.grey
                            : Colors.black),
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 18,
                    color: Colors.grey,
                  ),
                ],
              ),
            ),
            onTap: () => _selectCategory(context),
          ),
          CustomDivider(),
          PrimaryLabel('标题'),
          EditTextField(
            maxLines: 1,
            hintText: '请输入标题',
            controller: _titleController,
          ),
          CustomDivider(),
          PrimaryLabel('内容'),
          EditTextField(
            maxLines: 10,
            maxLength: 500,
            hintText: '来吧，尽情发挥吧！',
            controller: _contentController,
          ),
          CustomDivider(),
          PrimaryLabel(
            '上传图片',
            trailing: Text('${_images.length}/$maxImageCount'),
          ),
          Container(
            height: 110,
            color: Colors.white,
            width: double.maxFinite,
            alignment: Alignment.topLeft,
            padding: EdgeInsets.all(10),
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              itemBuilder: (c, i) {
                if (i == _images.length) {
                  return ItemAdd(onTap: _selectImages);
                } else {
                  return InkWell(
                    onTap: () {
                      CommonUtils.openGallery(
                          context,
                          _uploadedImages
                              .map((e) => Urls.BASE_URL + e)
                              .toList(),
                          i);
                    },
                    child: ItemImagePreview(
                      _images[i],
                      onTap: () {
                        // 删除图片时，判断已上传图片列表中是否包含这张照片。
                        if (_uploadedImages.length > i) {
                          _uploadedImages.removeAt(i);
                        }
                        setState(() {
                          _images.removeAt(i);
                        });
                      },
                    ),
                  );
                }
              },
              itemCount: _images.length == maxImageCount
                  ? _images.length
                  : _images.length + 1,
              padding: EdgeInsets.only(left: 0),
              separatorBuilder: (BuildContext context, int index) {
                // 给最后一个加号前面添加间距。
                return SizedBox(
                  width: _images.length > 0 && index == _images.length - 1
                      ? 13
                      : 0,
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  void _selectImages() async {
    CommonUtils.hideKeyboard(context);
    try {
      List<Asset> value = await MultiImagePicker.pickImages(
        maxImages: maxImageCount,
        selectedAssets: _images,
      );
      if (mounted) {
        setState(() {
          _images = value;
        });
        if (_images.isNotEmpty) {
          _uploadImages();
        }
      }
    } on Exception catch (e) {
      Log.d(_tag, e);
    }
  }

  /// 图片上传
  void _uploadImages() async {
    DialogUtils.showWaitDialog(context);
    FormData formData = FormData.fromMap({});
    formData.files.addAll((await CommonUtils.images2MapEntry(_images)));
    var value = await XHttp.uploadFiles(
      Urls.UPLOAD,
      formData,
    );
    if (value != null) {
      ListResponse response = ListResponse.fromJson(value);
      if (response.code == 1) {
        _uploadedImages = List<String>.from(response.data);
      }
    }
    Navigator.pop(context);
  }

  _send() async {
    CommonUtils.hideKeyboard(context);
    if (_categoryIndex == null) {
      ToastUtil.show('请选择一个类别', context);
      return;
    }
    if (_titleController.text.trim().isEmpty) {
      ToastUtil.show('标题不能为空', context);
      return;
    }
    if (_contentController.text.trim().isEmpty) {
      ToastUtil.show('内容不能为空', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var params = {
      "postInfoTitle": _titleController.text.trim(),
      "postInfoContent": _contentController.text.trim(),
      "postInfoType": widget.categories[_categoryIndex].value,
      "createdBy": SPUtils.getUser().id,
    };
    if (_uploadedImages.isNotEmpty) {
      params['postImages'] = _uploadedImages.join(',');
    }
    var data =  await XHttp.postJson(Urls.moment_save, params);
    Navigator.pop(context);
    if (data!=null) {
      // 创建成功，返回
      Navigator.pop(context, true);
    }
  }
}
